/*      $Id: cgi.c,v 1.3 2006/03/14 02:52:41 jfb Exp $    */
/*
 * Copyright (c) 2003 Jean-Francois Brousseau <phrakt@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <canopy/log.h>
#include <canopy/string.h>

#include <http/msg.h>
#include <http/http.h>
#include <http/entity.h>

#include "mod_cgi.h"

static int  mod_cgi_setupenv  (http_msg_t *);


/*
 * mod_cgi_exec()
 *
 *
 */
int
mod_cgi_exec(http_msg_t *req)
{
	int argc, status;
	pid_t pid;
	char *argv[16];

	if ((pid = fork()) == -1) {
		cnp_log(CNP_LOG_ERR, "failed to fork for CGI");
		return (-1);
	}

	if (pid == 0) {
		argc = 0;
		argv[argc++] = req->msg_req.req_url->uri_path;
		argv[argc++] = NULL;

		/* we're in the child, remap the descriptors */
		mod_cgi_setupenv(req);


		execv(argv[0], argv);
	}
	else {
		/* we're in the parent, wait for the child to finish */
		waitpid(pid, &status, 0);
	}



}

/*
 * mod_cgi_setupenv()
 *
 * Setup the environment of a subprocess according to the CGI specification.
 */
static int
mod_cgi_setupenv(http_msg_t *req)
{
	char buf[64];

	setenv("GATEWAY_INTERFACE", CGI_VERSION_STRING, 1);
	setenv("SERVER_SOFTWARE", "mod_cgi/0.1", 1);

	setenv("SERVER_NAME", req->msg_req.req_url->uri_host, 1);

	/* request-related variables */
	setenv("REQUEST_METHOD", "GET", 1);
	setenv("QUERY_STRING", req->msg_req.req_url->uri_query, 1);

	/* content-related variables */
	if (req->msg_entity != NULL) {
		snprintf(buf, sizeof(buf), "%llu",
		    (unsigned long long)req->msg_entity->ent_size);
		setenv("CONTENT_LENGTH", buf, 1);
		setenv("CONTENT_TYPE", req->msg_entity->ent_media, 1);
	}



}
